package com.yxh.bigdata.mapreduce.fensi;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SharedFriendsStepTwo {

    static class  SharedFriendsTwoMapper extends Mapper<LongWritable, Text, Text, Text> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] split = line.split("\t");
            context.write(new Text(split[0]), new Text(split[1]));

        }
    }


    static class SharedFriendsTwoReducer extends Reducer<Text, Text, Text, Text>{

        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            StringBuilder sb = new StringBuilder();
            values.forEach(text -> {
                sb.append(text.toString()).append(",");
            });
            context.write(key, new Text(sb.toString()));
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);

        job.setJarByClass(SharedFriendsStepTwo.class);

        job.setMapperClass(SharedFriendsTwoMapper.class);
        job.setReducerClass(SharedFriendsTwoReducer.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        //指定job的输入原始文件所在目录
        FileInputFormat.setInputPaths(job, new Path("D:\\bigdata\\fensi\\output1"));
        //指定job的输出结果所在目录
        FileOutputFormat.setOutputPath(job, new Path("D:\\bigdata\\fensi\\output2"));

        boolean res = job.waitForCompletion(true);
        System.exit(res?0:1);
    }
}
